package net.ib.mtalk.ui.buddy.contact;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

import net.ib.mntalk.protocol.Common.Name;
import net.ib.mtalk.R;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.ContactTable;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct;
import net.ib.mtalk.ui.buddy.item.BuddyUUIDItem;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContacts.Entity;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class BuddyContactAdapter extends CursorAdapter implements OnClickListener{

	private int mLayout;
	private LayoutInflater inflater;
	private boolean mShowcheckbox;
	private ArrayList<Character> temp_group = new ArrayList<Character>();
	private List<Long> buddy_list;
	private List<Long> checked_item;
	private List<Integer> mArr_group;

	private LayoutInflater mInflater;
	public static final char HANGUL_BEGIN_UNICODE = 44032; // 가
	public static final char HANGUL_END_UNICODE = 55203; // 힣
	public static final char HANGUL_BASE_UNIT = 588;//각자음 마다 가지는 글자수
	public static final char[] INITIAL_SOUND = { 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ',
        'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' };
	private char new_letter;
	private String new_name;
	
	public BuddyContactAdapter(Context context, Cursor c, int flags, boolean showcheckbox, List<Long> buddyList, List<Long> checked_item, List<Integer> arr_group) {
		super(context, c, flags);
		mLayout = R.layout.list_item_contact;
		this.mShowcheckbox = showcheckbox;
		this.buddy_list = buddyList;
		this.checked_item = checked_item;
		this.mArr_group = arr_group;
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		inflater = LayoutInflater.from(context);
		View v = inflater.inflate(mLayout, parent, false);
	
		ViewHolder holder = new ViewHolder();
		holder.item = (LinearLayout) v.findViewById(R.id.llayout01);
		holder.item1 = (RelativeLayout) v.findViewById(R.id.rlayoutGroup);
		holder.mGroupName = (TextView) v.findViewById(R.id.buddy_group_name);
		holder.mGroupParticipants = (TextView) v.findViewById(R.id.buddy_group_participants);
		
		holder.item2 = (RelativeLayout) v.findViewById(R.id.rlayoutChild);
		holder.mChildCheck = (CheckBox) v.findViewById(R.id.buddy_child_check);
		holder.mProfile = (ImageView) v.findViewById(R.id.buddy_child_profile);
		holder.mBirthdayImage = (ImageView) v.findViewById(R.id.birthday_img);
		holder.mBirthdayImage.setVisibility(View.GONE);
		
		holder.mChildName = (TextView) v.findViewById(R.id.buddy_child_name);
		holder.mRelationImage = (ImageView) v.findViewById(R.id.buddy_relation_img);
		holder.mStatus = (TextView) v.findViewById(R.id.buddy_child_status_msg);
		holder.mStatus.setVisibility(View.GONE);
		
		if(!mShowcheckbox){
			holder.mChildCheck.setVisibility(View.GONE);
		} else {
			holder.mChildCheck.setVisibility(View.VISIBLE);
		}
		
		v.setTag(holder);
		return v;
	}
	
	private static class ViewHolder {
		LinearLayout item;
		RelativeLayout item1;
		TextView mGroupName;
		TextView mGroupParticipants;
		
		RelativeLayout item2;
		CheckBox mChildCheck;
		ImageView mProfile;
		ImageView mBirthdayImage;
		TextView mChildName;
		TextView mStatus;
		ImageView mRelationImage;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
            throw new IllegalStateException("this should only be called when the cursor is valid");
        }
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException("couldn't move cursor to position " + position);
        }

        View v;
        if (convertView == null) {
            v = newView(mContext, mCursor, parent);
        } else {
            v = convertView;
        }
        
        /** 초성을 판별하여 인덱스 생성*/
        String a = mCursor.getString(mCursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME));
        if(a == null || "".equals(a)){
        	a = " ";
        }
        char b = a.charAt(0);
        char c;
        if(b < HANGUL_BEGIN_UNICODE){
        	c = b;
        } else{
        	c = INITIAL_SOUND[(b-HANGUL_BEGIN_UNICODE)/HANGUL_BASE_UNIT];
        }
        
        new_letter = c;
        new_name = Character.toString(new_letter);
        if(mArr_group.contains(mCursor.getPosition()) || mCursor.getPosition() == 0){
        	v.findViewById(R.id.rlayoutGroup).setVisibility(View.VISIBLE);
        } else {
        	v.findViewById(R.id.rlayoutGroup).setVisibility(View.GONE);
        }
        
        bindView(v, mContext, mCursor);
        return v;
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		ViewHolder holder = (ViewHolder)view.getTag();
		Bitmap photo = null;
		int contactId = cursor.getColumnIndexOrThrow(Contacts._ID);
		int contactName = cursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME);
		
		long raw_id = cursor.getLong(contactId);
		Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, raw_id);
		InputStream photoDataStream = Contacts.openContactPhotoInputStream(mContext.getContentResolver(), contactPhotoUri);
		photo = BitmapFactory.decodeStream(photoDataStream);
		
		if(photo != null){
			holder.mProfile.setImageBitmap(photo);
		} else {
			holder.mProfile.setImageResource(R.drawable.pic_default_small);
		}
		
		if(checked_item.contains(raw_id)){
			holder.mChildCheck.setChecked(true);
		} else {
			holder.mChildCheck.setChecked(false);
		}
		
		holder.mChildCheck.setOnClickListener(this);
		
		if(buddy_list.contains(raw_id)) holder.mRelationImage.setVisibility(View.VISIBLE);
		else holder.mRelationImage.setVisibility(View.GONE);
		
		holder.mChildName.setText(cursor.getString(contactName));
		holder.mGroupName.setText(new_name);
		
		holder.mChildCheck.setTag(raw_id);
	}
	
	@Override
	public void changeCursor(Cursor cursor) {
		super.changeCursor(cursor);
	}
	
	@Override
	public Cursor swapCursor(Cursor newCursor) {
		return super.swapCursor(newCursor);
	}
	
	public Bitmap getPhoto(ContentResolver contentResolver, Long contactId){
		Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
		
		InputStream photoDataStream = Contacts.openContactPhotoInputStream(contentResolver, contactPhotoUri);
		Bitmap  photo = BitmapFactory.decodeStream(photoDataStream);
		
		return photo;
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.buddy_child_check) {
			long id = (Long) v.getTag();
			if(!checked_item.contains(id)) {
				checked_item.add(id);
			} else if(checked_item.contains(id)) {
				checked_item.remove(id);
			}
		}
	}
	
	
//	public class ContactsItem {
//		public long id;
//		public String displayName;
//		public String phoneNumber;
//		public Uri photoUri;
//		
//		public long getId() {
//			return id;
//		}
//		public void setId(long id) {
//			this.id = id;
//		}
//		public String getDisplayName() {
//			return displayName;
//		}
//		public void setDisplayName(String displayName) {
//			this.displayName = displayName;
//		}
//		public String getPhoneNumber() {
//			return phoneNumber;
//		}
//		public void setPhoneNumber(String phoneNumber) {
//			this.phoneNumber = phoneNumber;
//		}
//		public Uri getPhotoUri() {
//			return photoUri;
//		}
//		public void setPhotoUri(Uri photoUri) {
//			this.photoUri = photoUri;
//		}
//	}

}
